package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {
    @Setter
    private IEmployeeService employeeService;
    @Setter
    private IRoleService roleService;
    @Setter
    private IPermissionService permissionService;

    @Override
    public String getName() {
        return "UserRealm";
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取页面传入的用户名
        String principal = (String) token.getPrincipal();
        System.out.println(principal);
        //查询数据库
        Employee currentUser = employeeService.selectUsername(principal);
        //无此用户
        if (currentUser == null) {
            return null;
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(currentUser, currentUser.getPassword(), getName());
        return authenticationInfo;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        List<String> roles = new ArrayList<String>();
        List<String> permissions = new ArrayList<String>();

        //获取当前用户
        Employee currentUser = (Employee) principals.getPrimaryPrincipal();
        //超级管理员
        if (currentUser.isAdmin()) {
            //拥有所有角色/权限
            List<Role> list = roleService.getAll();
            for (Role role : list) {
                roles.add(role.getSn());
            }
            permissions.add("*:*");
        } else {
            //查询当前用户的角色/权限
            Long id = currentUser.getId();
            roles = roleService.queryRoleSnByEmpId(currentUser.getId());
        //TODO test环境无权限约束
           permissions = permissionService.queryPermissionResourceByEmpId(currentUser.getId());
            //permissions.add("*:*");
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //("HR MGR", "ORDER MGR"));
        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }
}